/**
 * 适配iOS全面屏【iPhone X】
 * @author lawrence
 * @date 2019-03-14
 */
import React, {PureComponent} from "react";
import {DeviceInfo, SafeAreaView, StyleSheet, View} from "react-native";
import {isPhoneX} from "../../tools/ScreenUtil";

type Props = {
    topColor: string,           // 顶部安全区域适配颜色
    bottomColor: string,        // 底部安全区域适配颜色
    enablePlus: boolean,        // 是否使用SafeAreaViewPlus, true-SafeAreaViewPlus, false-SafeAreaView
    topInset: boolean,          // 是否显示顶部安全区域 true-显示，false-不显示
    bottomInset: boolean,       // 是否显示底部安全区域 true-显示，false-不显示
}

type State = {}

export default class SafeAreaViewPlus extends PureComponent<Props, State> {
    static defaultProps = {
        topColor: 'transparent',
        bottomColor: 'transparent',
        enablePlus: true,
        topInset: true,
        bottomInset: false,
    };

    render() {
        const {enablePlus} = this.props;
        return enablePlus ? this._safeAreaViewPlus() : this._safeAreaView();
    }

    /**
     * 使用系统SafeAreaView做为根视图
     * @return {*}
     * @private
     */
    _safeAreaView = () => {
        return (
            <SafeAreaView style={[styles.container, this.props.style]} {...this.props}>
                {this.props.children}
            </SafeAreaView>
        )
    };

    /**
     * 使用自定义SafeAreaViewPlus做为根视图
     * @return {*}
     * @private
     */
    _safeAreaViewPlus = () => {
        const {children, topColor, bottomColor, topInset, bottomInset} = this.props;
        return (
            <View style={[styles.container, this.props.style]} {...this.props}>
                {this._safeTopView(topColor, topInset)}
                {children}
                {this._safeBottomView(bottomColor, bottomInset)}
            </View>
        )
    };

    /**
     * 自定义SafeAreaViewPlus，顶部安全区域
     * @param color 背景颜色
     * @param inset 是否显示顶部安全区域
     * @private
     */
    _safeTopView = (color, inset) => {
        return isPhoneX() && inset ?
            <View style={[styles.topSafeArea, {backgroundColor: color}]} /> : null;
    };

    /**
     * 自定义SafeAreaViewPlus，底部安全区域
     * @param color 背景颜色
     * @param inset 是否显示底部安全区域
     * @private
     */
    _safeBottomView = (color, inset) => {
        return isPhoneX() && inset ?
            <View style={[styles.bottomSafeArea, {backgroundColor: color}]} /> : null;
    };

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    topSafeArea: {
        height: 44,
    },
    bottomSafeArea: {
        height: 34,
    }
});
